import os
import time

from app.admin import admin
from flask import render_template, request, jsonify, session, redirect, url_for, flash
from app.utils.models import User, Book, Comment, Item
from app.app import db

UPLOAD_PATH = os.path.join(os.path.dirname(__file__), '../static/imgs')


@admin.route("/")
def index():
    if session.get('admin_id'):
        admin = User.query.get(session['admin_id'])
        return render_template("admin/home.html", admin=admin)
    else:
        return render_template('user/404.html')


@admin.route("/item")
def item_view():
    if session.get('admin_id'):
        page = request.args.get('page', 1, type=int)
        admin = User.query.get(session['admin_id'])
        # books = Book.query.all()
        page_book = Book.query.paginate(page=page, per_page=10)
        return render_template("admin/item.html", books=page_book, admin=admin, page=page_book)
    else:
        return render_template('user/404.html')


@admin.route("/delete-item/<int:book_id>", methods=["POST"])
def delete_book(book_id):
    print(book_id)
    Book.query.filter(Book.book_id == book_id).delete()
    db.session.commit()  # 提交事务，将更改保存到数据库
    return jsonify({'valid': '0', 'msg': '删除成功！'})


@admin.route("/add-item/", methods=["POST"])
def add_item():
    item_name = request.form.get('item_name')
    item_author = request.form.get('item_author')
    item_desc = request.form.get('item_desc')
    derive = request.form.get('derive')
    price = request.form.get('price')
    if 'photo' not in request.files:
        flash('文件没有上传！')
        return redirect(url_for('admin.item_view'))
    img_file = request.files['photo']
    if img_file.filename == '':
        flash('没有选择文件！')
        return redirect(url_for('admin.item_view'))
    if not img_file.content_type.startswith('image/'):
        flash('只能上传图片！')
        return redirect(url_for('admin.item_view'))
    filename = img_file.filename
    base, ext = os.path.splitext(filename)
    timestamp = int(time.time() * 1000)
    unique_filename = f"{base}_{timestamp}{ext}"
    # print(unique_filename)
    img_file.save(os.path.join(UPLOAD_PATH, unique_filename))
    # print(item_name, item_author, item_desc, filename,img_file.filename)
    book = Book(book_name=item_name, book_author=item_author, price=price, desc=item_desc, derive=derive,
                photo='../../static/imgs/' + unique_filename)
    db.session.add(book)
    db.session.commit()
    flash('商品添加成功！')
    return redirect(url_for('admin.item_view'))


@admin.route('/upd-item', methods=['POST'])
def upd_item():
    book_id = request.form.get('id')
    item_name = request.form.get('item_name')
    item_author = request.form.get('item_author')
    item_desc = request.form.get('item_desc')
    derive = request.form.get('derive')
    price = request.form.get('price')
    if 'photo' not in request.files:
        flash('文件没有上传！')
        return redirect(url_for('admin.item_view'))
    img_file = request.files['photo']
    if img_file.filename == '':
        flash('没有选择文件！')
        return redirect(url_for('admin.item_view'))
    if not img_file.content_type.startswith('image/'):
        flash('只能上传图片！')
        return redirect(url_for('admin.item_view'))
    filename = img_file.filename
    base, ext = os.path.splitext(filename)
    timestamp = int(time.time() * 1000)
    unique_filename = f"{base}_{timestamp}{ext}"
    # print(book_id, "+", item_name, item_author, item_desc, price, unique_filename)
    # print(unique_filename)
    img_file.save(os.path.join(UPLOAD_PATH, unique_filename))
    # print(item_name, item_author, item_desc, filename,img_file.filename)

    book = Book.query.get(book_id)
    book.book_name = item_name
    book.book_author = item_author
    book.price = price
    book.desc = item_desc
    book.derive = derive
    book.photo = '../../static/imgs/' + unique_filename
    db.session.add(book)
    db.session.commit()
    flash('商品修改成功！')
    return redirect(url_for('admin.item_view'))


@admin.route('/order')
def order():
    if session.get('admin_id'):
        admin = User.query.get(session['admin_id'])
        items = Item.query.all()
        orders = []
        users = []
        for item in items:
            user = User.query.get(item.user_id)
            users.append(user)
            book = Book.query.get(item.book_id)
            # TODO 将user和book和为一个对象
            order = {
                'item_id': item.item_id,
                'user': user.to_dict(),
                'book': book.to_dict(),
                'number': item.number
            }
            orders.append(order)
        # print(orders)
        users = list(set(users))
        return render_template('admin/order.html', orders=orders, users=users, admin=admin)
    else:
        return render_template('user/404.html')


@admin.route('get_item/<int:item_id>', methods=['GET'])
def get_item(item_id):
    item = Item.query.get(item_id)
    book = Book.query.get(item.book_id)
    user = User.query.get(item.user_id)
    item = {
        'book': book.to_dict(),
        'user': user.to_dict(),
        'item': item.to_dict()
    }
    return jsonify({'valid': '0', 'msg': '查询成功！', 'item': item})


@admin.route('/users')
def user():
    if session.get('admin_id'):
        page = request.args.get('page', 1, type=int)
        admin = User.query.get(session['admin_id'])
        # users = User.query.all()
        page_user = User.query.paginate(page=page, per_page=10)
        return render_template("admin/user.html", users=page_user, page=page_user, admin=admin)
    else:
        return render_template('user/404.html')


@admin.route('/upd_user', methods=['POST'])
def update_user():
    # 获取表单数据
    user_id = request.form.get('id')
    username = request.form.get('item_name')
    password = request.form.get('item_author')
    user_role = request.form.get('radios')
    print(user_id, username, password, user_role)
    user = User.query.get(user_id)
    user.name = username
    user.password = password
    if user_role == 'admin':
        user.admin = 1
    else:
        user.admin = 0
    db.session.add(user)
    try:
        db.session.commit()
        flash('修改成功！')
        return redirect(url_for('admin.user'))
    except Exception as e:
        db.session.rollback()
        flash("信息错误，修改失败！")
        return redirect(url_for('admin.user'))


@admin.route('search_view', methods=['GET'])
def search_view():
    search = request.args.get('search')
    text = request.args.get('text')
    print(text)
    if text == 'book':
        # books = Book.query.filter(Book.book_name.contains(search)).all()
        books = [book.to_dict() for book in Book.query.filter(Book.book_name.contains(search)).all()]
        return jsonify({'valid': '0', 'msg': '查询成功！', 'books': books})
    elif text == 'order':
        # TODO key->id->item->组合成为order
        book = Book.query.filter(Book.book_name.contains(search)).first()
        items = Item.query.filter_by(book_id=book.book_id).all()
        orders = []
        users = []
        for item in items:
            user = User.query.get(item.user_id)
            users.append(user.to_dict())
            order = {
                'order_id': item.item_id,
                'user': user.to_dict(),
                'book': book.to_dict(),
                'number': item.number
            }
            orders.append(order)
        # users = list(set(users))
        users = [dict(t) for t in {tuple(user.items()) for user in users}]
        return jsonify({'valid': '0', 'msg': '查询成功！', 'orders': orders, 'users': users})
    elif text == 'user':
        users = [user.to_dict() for user in User.query.filter(User.name.contains(search)).all()]
        # users = User.query.filter(User.username.contains(search))
        return jsonify({'valid': '0', 'msg': '查询成功！', 'users': users})
    return jsonify({'valid': '0', 'msg': '系统错误'})
